package nl.gamayun.whohasit.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import nl.gamayun.whohasit.R;
import nl.gamayun.whohasit.WhoHasIt;
import nl.gamayun.whohasit.WhoHasItDBAdapter;
import nl.gamayun.whohasit.WhoHasItHandler;
import nl.gamayun.whohasit.WhoHasItHandlerImpl;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.preference.PreferenceManager;
import android.util.Log;

public class WhoHasItUtils {

	private static final String TAG = WhoHasItUtils.class.getSimpleName();
	private static final Resources resources = WhoHasIt.getContext().getResources();
	private static final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(WhoHasIt.getContext());
	

	public final static SimpleDateFormat LOAN_DATE_TIME_FORMAT = new SimpleDateFormat(
			"dd MMM yyyy HH:mm:ss");
	public final static SimpleDateFormat LOAN_DATE_FORMAT = new SimpleDateFormat(
			"dd MMM yyyy");
	

	private static WhoHasItHandler whoHasItHandler;
	private static PackageManager pm = WhoHasIt.getContext().getPackageManager();
	

	public static WhoHasItHandler getWhoHasItHandler(Context context) {
		Log.d(TAG, "getWhoHasItHandler()");
		if (whoHasItHandler == null) 
		{
			Log.d(TAG, "getWhoHasItHandler().new Handler");
			whoHasItHandler = new WhoHasItHandlerImpl(context);
		}
		return whoHasItHandler;
	}

	public static String getAppVersion() {
		String version = "xx.yy.zzz";
		if (pm != null) {
			try {
				PackageInfo pi = pm.getPackageInfo(WhoHasIt.getContext()
						.getPackageName(), PackageManager.GET_CONFIGURATIONS);
				version = pi.versionName;
			} catch (NameNotFoundException e) {
				Log.e(TAG, "getAppVersion", e);
			}
		}
		return version;
	}

	public static Calendar getDefaultReturnDate()
	{
		Calendar returnDate = Calendar.getInstance();
		String preferences_return_key = resources.getString(R.string.preferences_return_key);
		Integer choice = Integer.valueOf(sharedPrefs.getString(preferences_return_key, "4"));
		Log.d(TAG, "getDefaultReturnDate for : "+ choice);
		switch (choice)
		{
			case 1:
				returnDate.add(Calendar.WEEK_OF_YEAR, 1);
				break;
			case 2:
				returnDate.add(Calendar.WEEK_OF_YEAR, 2);
				break;
			case 3:
				returnDate.add(Calendar.WEEK_OF_YEAR, 3);
				break;
			case 4:
				returnDate.add(Calendar.MONTH, 1);
				break;
			case 5:
				returnDate.add(Calendar.MONTH, 2);
				break;
			case 6:
				returnDate.add(Calendar.MONTH, 3);
				break;
			case 7:
				returnDate.add(Calendar.MONTH, 6);
				break;
			case 8:
				returnDate.add(Calendar.YEAR, 1);
				break;
			default:
				returnDate.add(Calendar.MONTH, 1);
		}
		
		return returnDate;
	}

}
